import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Tabs, Row, Select, Table, Avatar } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getUserList, getSupplierList, getStoreList } from '@/services/userCenter/userList/all'
import { router } from 'umi'
import { exportsExcel } from '@/utils/utils'

const { Option } = Select

const { TabPane } = Tabs

// 表头
const columns = [
  {
    title: '微信头像',
    dataIndex: 'userHeadImg',
    key: 'userHeadImg',
    align: 'center',
    render: userHeadImg => <Avatar shape="square" size="large" src={userHeadImg} />
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    align: 'center'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    align: 'center'
  },
  {
    title: '订单数/消费额',
    dataIndex: 'totalConsumption',
    key: 'totalConsumption',
    align: 'center'
  },
  {
    title: '账户余额',
    dataIndex: 'cashTotal',
    key: 'cashTotal',
    align: 'center'
  },
  {
    title: '最后消费时间',
    dataIndex: 'lastTradeTime',
    key: 'lastTradeTime',
    align: 'center'
  },
  {
    title: '注册时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center'
  },
  {
    title: 'openId',
    dataIndex: 'payRecord',
    key: 'payRecord',
    align: 'center'
  }
]

const Wx = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [userList, setUserList] = useState([])
  const [total, setTotal] = useState(1)
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [record, setRecord] = useState({})
  const [orderByCondition, setOrderByCondition] = useState('last_trade_time desc')
  const [supplierList, setSupplierList] = useState([])
  const [storeList, setStoreList] = useState([])
  const [statusList, setStatusList] = useState([
    {
      id: '1',
      name: '正常'
    },
    {
      id: '0',
      name: '已删除'
    }
  ])
  const [registerRes, setRegisterRes] = useState('WX')

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      console.log(record)
    },
  }

  useEffect(() => {
    init()
  }, [])
  const init = async () => {
    let params = {
      pageNo,
      pageSize,
      orderByCondition,
      registerRes
    }
    await getUserLists(params)
    await getSupplierLists()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields(async (err, values) => {
      console.log('Received values of form: ', values)
      let params = {
        pageNo,
        pageSize,
        orderByCondition,
        supplierId: values.supplierId,
        storeId: values.storeId,
        nickname: values.nickname,
        phone: values.phone,
        loginName: values.loginName,
        status: values.status,
        registerRes
      }
      await getUserLists(params)
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="所属商户" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('supplierId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
                onChange={getStoreLists}
              >
                { supplierList && supplierList.map(r => <Option key={r.id} value={r.id}>{r.merchantName}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="选择门店" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('storeId', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { storeList && storeList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="昵称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('nickname', {})
              (<Input placeholder="请输入昵称" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="手机号" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('phone', {})
              (<Input placeholder="请输入手机号" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="用户名" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('loginName', {})
              (<Input placeholder="请输入用户名" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="选择状态" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} >
            {getFieldDecorator('status', {})
              (<Select
                style={{ width: '100%' }}
                showSearch
                filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                placeholder="请选择"
              >
                { statusList && statusList.map(r => <Option key={r.id} value={r.id}>{r.name}</Option>)}
              </Select>)}
          </Form.Item>
        </Col>
      </Row>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      // 用户详情
      case 12:
        router.push({ pathname: '/userCenter/userList/info', query: { id: record[0].id } });
        break
      // 导出excel
      case 97:
        exportsExcel({
          columns,
          data: userList,
          title: '微信会员'
        })
        break
    }
  }
  // 获取商铺列表
  const getUserLists = async (params) => {
    let res = await getUserList(params)
    if (res.code === '0') {
      setUserList(res.data)
      setTotal(res.iTotalDisplayRecords)
    } else {
      alert('您点的太快了，请刷新页面')
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      let params = {
        pageNo: page,
        pageSize,
        orderByCondition,
        registerRes
      }
      getUserLists(params)
    }
  }
  // 切换tab
  const changeTabs = async (key) => {
    // console.log(key)
    let params = {
      pageNo,
      pageSize,
      orderByCondition,
      registerRes
    }
    switch (key) {
      case '0':
        params.userStatus = ''
        break
      case '1':
        params.userStatus = '1'
        break
      case '2':
        params.userStatus = '2'
        break
    }
    handleReset()
    await getUserLists(params)
  }
  // 获取商户列表
  const getSupplierLists = async () => {
    let res = await getSupplierList()
    setSupplierList(res.data)
  }
  // 获取门店列表
  const getStoreLists = async (supplierId) => {
    let params = {
      pageSize: 9999,
      supplierId
    }
    let res = await getStoreList(params)
    setStoreList(res.data)
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Tabs defaultActiveKey="0" onChange={changeTabs}>
        <TabPane tab="所有用户" key="0">
        </TabPane>
        <TabPane tab="活跃用户" key="1">
        </TabPane>
        <TabPane tab="沉睡用户" key="2">
        </TabPane>
      </Tabs>
      <Table
        columns={columns}
        dataSource={userList}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
   </PageHeaderWrapper>
  )
}

export default Form.create()(Wx)
